<template>
    <div class="search">
        <el-autocomplete clearable placeholder="请输入想查询的医院名称" :fetch-suggestions="fetchHospitalInfoData"
            :trigger-on-focus="false" v-model="hosName" @select="toDetail" />
        <el-button type="primary" :icon="Search">搜索</el-button>
    </div>
</template>

<script setup lang="ts" name="Search">
//引入element图标
import { Search } from '@element-plus/icons-vue'
import { ref } from 'vue';
// 引入模糊匹配请求方法
import { reqHospitalKeyInfoData } from '@/api/home/index'
import type { HospitalInfoData, Hospital } from '@/api/home/type'
import { useRouter } from 'vue-router';

// 引入路由
const $router = useRouter()

//收集用户输入的搜索内容
const hosName = ref<string>('')

//搜索框的回调收集函数
const fetchHospitalInfoData = async (keyword: string, cb: Function) => {
    //当用户完成一次输入后，回调函数执行，进行一次模糊搜索
    const res: HospitalInfoData = await reqHospitalKeyInfoData(keyword)
    //整理数据，变成组件需要的形式
    const showData = res.data.map((item: Hospital) => {
        return {
            //展示医院的名字
            value: item.hosname,
            //存储医院的唯一编码，用于后续用户点击后跳转
            hosCode: item.hoscode,
        }
    })
    //给组件提供模糊搜索结果
    cb(showData)
}

// 用户点击某一个推荐项后跳转至该医院的详情页
const toDetail = (item: any) => {
    // query参数为医院的唯一编码
    $router.push({ path: '/hospital', query: { hoscode: item.hosCode } })
}


</script>

<style scoped lang="scss">
/* 深度选择器:>>>  /deep/ :deep */
.search {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;

    :deep(.el-input__wrapper) {
        width: 600px;
        margin-right: 10px;
    }
}
</style>